import { Component, OnInit, Input, Inject, Output, EventEmitter } from '@angular/core';
import { API_CONFIG } from 'src/app/service/service.module';
import { NzMessageService, NzModalService, NzUploadFile } from 'ng-zorro-antd';
import { Observable, Observer } from 'rxjs';

@Component({
  selector: 'app-adver-editor',
  templateUrl: './adver-editor.component.html',
  styleUrls: ['../../editor.less']
})
export class AdverEditorComponent implements OnInit {
  uploadUrl: string | null = '';
  headers = null;
  loading = false;
  constructor(private msg: NzMessageService,
    @Inject(API_CONFIG) private uri: string,) { }
  @Input() selectEl = {
    type: 'advert',
    advertList: []
  }
  @Output() onRemove = new EventEmitter(null)
  @Output() onSave = new EventEmitter(null)
  ngOnInit(): void {
    this.uploadUrl = this.uri + '/custom/upload/live-cover';
    let ticket = window.sessionStorage['ticket'];
    this.headers = { 'Authorization': 'BasicAuth ' + ticket };
  }
  save() {
    this.onSave.emit()
  }
  remove(){
    this.onRemove.emit()
  }
  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.msg.error('只能上传图片!');
        observer.complete();
        return;
      }
      const isLt2M = file.size! / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.msg.error('图片必须小于 2MB!');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  };
  handleChange(info: { file: NzUploadFile }, index): void {
    switch (info.file.status) {
      case 'uploading':
        this.loading = true;
        break;
      case 'done':
        this.selectEl.advertList[index].backgroundImage = info.file.response.url;
        this.loading = false;
        this.save()
        break;
      case 'error':
        this.msg.error('Network error');
        this.loading = false;
        break;
    }
  }
  add() {
    this.selectEl.advertList.push({
      backgroundImage: '',
      link: ''
    })
    this.save()
  }
  delete(i) {
    this.selectEl.advertList.splice(i, 1)
    this.save()
  }
}
